package com.kll.tv.views.fragment.main

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.kll.carolinehmibiz.AccountManager
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetFamilyResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.MainContactFamilyProtocol
import com.kll.carolinehmibiz.presentation.presenter.MainContactFamilyPresenter
import com.kll.tv.base.views.MainBaseFragment
import com.kll.tv.databinding.FragmentMainContactfamilyBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.utils.TUICallingService
import com.kll.tv.views.NewContactActivity
import com.kll.tv.views.adapter.ContactFamilyAdapter
import com.tencent.liteav.trtccalling.model.TUICalling
import com.tencent.liteav.trtccalling.model.impl.TUICallingManager
import com.tencent.liteav.trtccalling.model.util.TUICallingConstants
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil

/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/7 22:19
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
 class MainContactFamilyFragmengt: MainBaseFragment<MainContactFamilyPresenter>(), MainContactFamilyProtocol.IView, ContactFamilyAdapter.OnFamilyListItemClickListener {

    private lateinit var binding: FragmentMainContactfamilyBinding
    private val mCallingManager = TUICallingManager.sharedInstance()
    private var data: ArrayList<GetFamilyResponse> = arrayListOf()
    private var adapter: ContactFamilyAdapter? = null

    // 临时数据
    val SDKAPPID = 1400374451
    var mCallName: String? = null
    var mCallType: TUICalling.Type?= null
    var mRoomId:String?=null

    // TUICallingService

    override fun createPresenter(): MainContactFamilyPresenter {
        return MainContactFamilyPresenter(requireContext(), this)
    }

    override fun initViewBinding(): View {
        binding = FragmentMainContactfamilyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun init() {
        // 初始化adapter
        if (adapter == null) {
            val familyListManager = LinearLayoutManager(context)
            familyListManager.orientation = LinearLayoutManager.VERTICAL
            binding.rvContent.layoutManager = familyListManager
            adapter = ContactFamilyAdapter(requireContext())
            binding.rvContent.adapter = adapter
            adapter!!.setOnFamilyListItemClickListener(this)
        }
        initData()
        initListener()
    }

    override fun onFragmentVisibleChange(isVisible: Boolean) {
        super.onFragmentVisibleChange(isVisible)

        if(isVisible)  {
            TUICallingService.getInstance(requireContext()).login()

            if(TUICallingService.getInstance(requireContext()).isLogin()) {
                var userInfo = AccountManager.getInstancce().getLoginUserInfo()

                binding.tvLoginStatus.text = "已登录账号：${userInfo?.tencent_user_id}"
            } else {
                binding.tvLoginStatus.text = "未登录"
            }
        }

    }

    private fun initData(){

//        var userInfo = mPresenter.getUserInfo()
//        var appId = mPresenter.getAppId()
//        var userSig = mPresenter.getUserSig()

//        if(userInfo != null && appId != null) {
//            TUILogin.init(requireContext(), appId.toInt(), null, object: V2TIMSDKListener() {
//                override fun onKickedOffline() {
//                    super.onKickedOffline()
//                }
//
//                override fun onUserSigExpired() {
//                    super.onUserSigExpired()
//                }
//            })
//
//            TUILogin.login(userInfo.tencent_user_id, GenerateTestUserSig.genTestUserSig(userInfo.tencent_user_id), object: V2TIMCallback {
//                override fun onSuccess() {
//                    ToastUtils.showLong("登录成功！")
//                }
//
//                override fun onError(p0: Int, p1: String?) {
////                binding.tvStatus.text = "p0:${p0}, p1:${p1}"
//                }
//            })
//        }

        // 加载数据
        loadData()
    }

    private fun initListener() {
        // 新建联系人
        binding.ivNewContact.setOnClickListener {
            startActivityForResult(Intent(context, NewContactActivity::class.java).putExtra("isFrom", 0), 1)
        }
        // 输入监听
        binding.editTextTextPersonName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val newData = arrayListOf<GetFamilyResponse>()
                for (index in data) {
                    if ((index.first_name + index.last_name).indexOf(s.toString()) != -1) {
                        newData.add(index)
                    }
                }
                adapter!!.data = newData
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        binding.editTextTextPersonName.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.editTextTextPersonName.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.editTextTextPersonName)
                }
            }

        })
    }

    private fun loadData() {
        mPresenter.getFamily()
    }

    override fun getRoomIdSuccess(tecentUserId: String,roomid: String) {
        call(tecentUserId,roomid)
    }

    override fun getRoomIdFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getFamily()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun getFamilySuccessed(data: ArrayList<GetFamilyResponse>) {
        this.data = data
        adapter!!.data = this.data
    }

    override fun getFamilyFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getFamily()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 获取用户活跃的腾讯云IM用户的id成功回调
     */
    override fun getTencentIdSuccessed(tencentUserId: String) {
        //获取腾讯IM成功后，获取房间号，开始通话
        mPresenter.getRoomId(tencentUserId)
    }

    /**
     * 获取用户活跃的腾讯云IM用户的id失败回调
     */
    override fun getTencentIdFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getFamily()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * item点击回调
     */
    override fun onFamilyItemClick(data: GetFamilyResponse) {
        val intent = Intent(context, NewContactActivity::class.java)
        val bundle = Bundle()
        bundle.putSerializable("data", data)
        intent.putExtra("data", bundle)
        intent.putExtra("isFrom", 1)
        startActivityForResult(intent, 1)
    }

    /**
     * 视频通话点击回调
     */
    override fun onFamilyVideoClick(tecentUserId: String) {
        mCallName = TUICallingConstants.TYPE_VIDEO
        mCallType =   TUICalling.Type.VIDEO
        mPresenter.getTencentId(tecentUserId);//AccountManager.getInstancce().getLoginUserInfo()!!.tencent_user_id)
    }

    /**
     * 语音通话点击回调
     */
    override fun onFamilyVoiceClick(tecentUserId: String) {
        mCallName = TUICallingConstants.TYPE_AUDIO
        mCallType =   TUICalling.Type.AUDIO
        mPresenter.getTencentId(tecentUserId);//AccountManager.getInstancce().getLoginUserInfo()!!.tencent_user_id)
    }

    /**
     * 拨打视频或语音
     */
    private fun call(tecentUserId: String,roomid: String){
        val userIDs = arrayOf(tecentUserId)
/*        val bundle = Bundle()
        bundle.putString(TUICallingConstants.PARAM_NAME_TYPE, mCallName)
        bundle.putStringArray(TUICallingConstants.PARAM_NAME_USERIDS, userIDs)
        bundle.putString(TUICallingConstants.PARAM_NAME_GROUPID, roomid)*/
//            TUICore.callService(TUIConstants.Service.TUI_CALLING, TUICallingConstants.METHOD_NAME_CALL, bundle);
        //            TUICore.callService(TUIConstants.Service.TUI_CALLING, TUICallingConstants.METHOD_NAME_CALL, bundle);
        TUICallingManager.sharedInstance().call(userIDs,roomid, mCallType)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1) {
            when (resultCode) {
                1 -> {
                    // 新建联系人回来
                    mPresenter.getFamily()
                }
                2 -> {
                    // 编辑联系人回来
                    mPresenter.getFamily()
                }
                3 -> {
                    // 删除完回来
                    mPresenter.getFamily()
                }
            }
        }
    }

}